package meijuli.com.join51.business.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.BankActivity;
import meijuli.com.join51.business.activity.FlowActivity;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.setpaypwd.PayPwdActivity;
import meijuli.com.join51.business.activity.SetPayPwdActivity;
import meijuli.com.join51.business.activity.WithDrawActivity;
import meijuli.com.join51.business.adapter.WalletAdapter;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.BankMsg;
import meijuli.com.join51.business.model.EventBean;
import meijuli.com.join51.business.model.UserWallet;
import meijuli.com.join51.business.model.Wallet;
import meijuli.com.join51.business.model.WalletData;
import com.jhx.common.widget.CommonDialog;
import retrofit2.Call;

/**
 * 钱包页面
 *
 * @author wenqin 2017-05-05 09:51
 */

public class WalletFragment extends BaseFragment implements
        WalletAdapter.OnWalletTopViewClickListener {
    RecyclerView mIntegralRv;
    SwipeRefreshLayout mSwipeRefresh;

    private WalletAdapter mWalletAdapter;
    private List<Wallet> mWalletList;
    private WalletData mData;
    private Call<HttpResponse<WalletData>> mCall;
    private Call<HttpResponse<String>> mRCall;
    private Call<HttpResponse<BankMsg>> call;
    private CommonDialog mDialog;
    private int mPwdIsExist = PayPwdActivity.SET_PASSWORD;
    private Dialog mNOBankCardDialog;
    private Runnable mRunnable;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wallet, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIntegralRv = view.findViewById(R.id.integral_rv);
        mSwipeRefresh = view.findViewById(R.id.swipe_refresh);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        load();
        initRvOptions();
        requestWallet();
    }

    private void initRvOptions() {
        mWalletList = new ArrayList<>();
        mIntegralRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mWalletAdapter = new WalletAdapter(getActivity(), mWalletList);
        mIntegralRv.setAdapter(mWalletAdapter);
        // 头部
        mWalletList.add(new Wallet());
        mWalletList.add(new Wallet(R.mipmap.icon_settle, "货款", Wallet.TYPE_SETTLE));
//        mWalletList.add(new Wallet(R.mipmap.icon_currency, "消费券", Wallet.TYPE_MONEY));
//        mWalletList.add(new Wallet(R.mipmap.icon_integral, "赠送积分券", Wallet.TYPE_INTEGRAL));
        mWalletAdapter.notifyDataSetChanged();

        mWalletAdapter.setOnItemClickListener(new WalletAdapter.OnItemClickListener() {
            @Override
            public void itemClick(int position) {
                onItemClick(mWalletList.get(position).getType());
            }
        });

        mWalletAdapter.setOnWalletTopViewClickListener(this);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWallet(false);
            }
        });

    }

    /**
     * 获取钱包信息
     *
     * @param isShowLoadingDialog
     */
    private void requestWallet(boolean isShowLoadingDialog) {
        if (!mSwipeRefresh.isRefreshing() && isShowLoadingDialog) {
            mSwipeRefresh.setRefreshing(true);
        }
        mCall = ApiManager.get().getApiService(ApiService.class).getWalletData();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<WalletData>() {

            @Override
            public void onSuccess(String url, WalletData data) {
                dismissRefreshDelay();
                if(data != null) {
                    mData = data;
                    updateList(data);
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                mSwipeRefresh.setRefreshing(false);
            }
        });
    }

    private void dismissRefreshDelay() {
        if (mRunnable == null) {
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    if (!isDetached() && mSwipeRefresh != null) {
                        mSwipeRefresh.setRefreshing(false);
                    }
                }
            };
        }
        mSwipeRefresh.postDelayed(mRunnable, 1000);
    }

    private void updateList(WalletData data) {
        UserWallet userWallet = data.getUserWallet();
        updateWallet(1, userWallet.getStringGoodsMoney());
        mWalletAdapter.notifyDataSetChanged();
    }

    private void updateWallet(int index, String money) {
        Wallet wallet = mWalletList.get(index);
        wallet.setPrice(money);
    }

    private void onItemClick(int type) {
        switch (type) {
                // 货款
            case Wallet.TYPE_SETTLE:
                // 消费券
            case Wallet.TYPE_MONEY:
                // 消费积分券
            case Wallet.TYPE_INTEGRAL:
                FlowActivity.start(getActivity(), type);
                break;
            default:

                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBean eventBean) {
        switch (eventBean.getStatus()) {
            case EventBean.STATUS_UPDATE_WALLET:
                requestWallet(false);
                break;
            default:

                break;
        }
    }

    private void requestWallet() {
        requestWallet(true);
    }

    private void requestBankCard() {
        showLoadingDialog();
        call = ApiManager.get().getApiService(ApiService.class).getBankCard();
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<BankMsg>() {

            @Override
            public void onSuccess(String url, BankMsg data) {
                dismissDialog();
                if(data == null || mData == null) {
                    return;
                }
                if(mData.getUserWallet().getHasPayPwd() == 0) {
                    if(mDialog == null && !getActivity().isFinishing()) {
                        mDialog = new CommonDialog(getActivity());
                    }
                    mDialog.setMessage("您尚未设定交易密码，如需进行“提现”操作，请前往“交易密码”进行设定！");
                    mDialog.setConfirmBtn("设置");
                    mDialog.setCancelBtn("取消");
                    mDialog.setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onConfirmClick(View view) {
                            tradingPwdView();
                        }

                        @Override
                        public void onCancelClick(View view) {

                        }
                    });
                    if(!mDialog.isShowing() && !getActivity().isFinishing()) {
                        mDialog.show();
                    }
                    return;
                }
                WithDrawActivity.start(getActivity(), data);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                if(errorCode == 7777) {
                    showNoBankCardDialog();
                }
            }
        });
    }

    private void showNoBankCardDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("您尚未绑定银行卡，如需进行“提现”操作，请前往“绑定银行卡”进行设定！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        BankActivity.start(getActivity());
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        mNOBankCardDialog = builder.create();
        mNOBankCardDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mNOBankCardDialog != null) {
            mNOBankCardDialog.dismiss();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void load() {
        mRCall = ApiManager.get().getApiService(ApiService.class).getPayPwd();
        HttpRequest.getRequest().autoRecycle(this).start(mRCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                mPwdIsExist = PayPwdActivity.UPDATE_PASSWORD;
            }
        });
    }

    @Override
    public void onBankView() {
        //银行卡
        BankActivity.start(getActivity());
    }

    @Override
    public void onWithdrawView() {
        //提现
        requestBankCard();
    }

    @Override
    public void tradingPwdView() {
        //交易密码
        Intent intent = new Intent(getActivity(), SetPayPwdActivity.class);
        intent.putExtra(PayPwdActivity.KEY_TYPE, mPwdIsExist);
        startActivity(intent);
    }
}
